package com.hardy.leecode;

import com.hardy.leecode.model.TreeNode;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Author: Hardy
 * Date:   2020/11/30
 * Description:
 * -
 * 剑指 Offer 32 - II. 从上到下打印二叉树 II
 *
 * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 *
 *  
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回其层次遍历结果：
 *
 * [
 *   [3],
 *   [9,20],
 *   [15,7]
 * ]
 *  
 *
 * 提示：
 *
 * 节点总数 <= 1000
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 **/
public class QueOffer32 {

    public static void main(String[] args) {

        TreeNode node = new TreeNode(3);
        TreeNode node1 = new TreeNode(9);
        TreeNode node2 = new TreeNode(20);
        TreeNode node3 = new TreeNode(15);
        TreeNode node4 = new TreeNode(7);

        node.left = node1;
        node.right = node2;

        node2.left = node3;
        node2.left = node4;

        System.out.println(new Solution().levelOrder(node));
    }

    static class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            if (root == null) return new LinkedList();
            Queue<TreeNode> q = new LinkedList();
            q.offer(root);

            List<List<Integer>> r = new LinkedList();
            while (!q.isEmpty()) {
                int size = q.size();
                List<Integer> a = new LinkedList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode n = q.poll();
                    a.add(n.val);

                    if (n.left != null) q.offer(n.left);
                    if (n.right != null) q.offer(n.right);
                }
                r.add(a);
            }
            return r;
        }
    }
}
